package com.wetao.module_homework;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.Choreographer;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.bumptech.glide.signature.ObjectKey;
import com.daquexian.flexiblerichtextview.FlexibleRichTextView;
import com.facebook.stetho.common.LogUtil;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.reflect.TypeToken;
import com.tstudy.blepenlib.data.BleDevice;
import com.tstudy.blepenlib.data.CoordinateInfo;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.EventBus.EventBusMessage;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.base.BaseResponse;
import com.wetao.lib_common.bean.request.CommitAssistantQuestionsOnlineReq;
import com.wetao.lib_common.bean.request.CommitAssistantQuestionsReq_vo;
import com.wetao.lib_common.bean.response.CommitAssistantAnswerResp;
import com.wetao.lib_common.bean.response.QueryExamQuestionsResponse;
import com.wetao.lib_common.bean.response.StudentExamQuestion;
import com.wetao.lib_common.finalParam.QuestionType;
import com.wetao.lib_common.greendao.DBUtils;
import com.wetao.lib_common.greendao.model.AssistantExamOnline;
import com.wetao.lib_common.greendao.model.AssistantQuestionOnline;
import com.wetao.lib_common.greendao.model.PagePictureOnline;
import com.wetao.lib_common.service.PlayService;
import com.wetao.lib_common.tsdBlePen.TsdPenUtil;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.BitmapLruCache;
import com.wetao.lib_common.utils.BitmapUtil;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.DialogXUtil;
import com.wetao.lib_common.utils.FileUtils;
import com.wetao.lib_common.utils.FormulaUtil;
import com.wetao.lib_common.utils.GsonUtil;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.QuestionTypeUtil;
import com.wetao.lib_common.utils.SPUtils;
import com.wetao.lib_common.utils.StringUtil;
import com.wetao.lib_common.utils.ToastUtil;
import com.wetao.lib_common.utils.oss.OssParams;
import com.wetao.lib_common.utils.oss.UploadOss;
import com.wetao.lib_common.view.OnMultiClickListener;
import com.wetao.module_homework.component.QuestionUtils;
import com.wetao.module_homework.contract.HomeworkLineActivityCon;
import com.wetao.module_homework.presenter.HomeworkLineActivityPre;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.scilab.forge.jlatexmath.core.AjLatexMath;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import cn.hzw.doodle.DoodleColor;
import cn.hzw.doodle.DoodleOnTouchGestureListener;
import cn.hzw.doodle.DoodleParams;
import cn.hzw.doodle.DoodleTouchDetector;
import cn.hzw.doodle.DoodleView;
import cn.hzw.doodle.IDoodleListener;
import cn.hzw.doodle.core.IDoodle;
import cn.hzw.doodle.core.IDoodleItemListener;
import cn.hzw.doodle.core.IDoodleSelectableItem;
import cn.hzw.doodle.core.IDoodleTouchDetector;
import io.github.kbiakov.codeview.classifier.CodeProcessor;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

@Route(path = ConstantArouter.PATH_HOMEWORK_LINEACTIVITY)
public class HomeworkLineActivity extends BaseActivity<HomeworkLineActivityCon.View, HomeworkLineActivityPre>
        implements HomeworkLineActivityCon.View {

    @BindView(R2.id.iv_close)
    ImageView ivClose;
    @BindView(R2.id.tab_scene)
    TabLayout tabScene;

    @BindView(R2.id.fl_doodle)
    FrameLayout flDoodle;
    @BindView(R2.id.bt_next_submit)
    AppCompatButton btNextSubmit;

    @BindView(R2.id.tv_title)
    AppCompatTextView tvTitle;
    @BindView(R2.id.ll_question_answer)
    LinearLayout llQuestionAnswer;
    @BindView(R2.id.tab_num)
    TabLayout tabNum;
    @BindView(R2.id.ll_question)
    LinearLayout llQuestion;
    @BindView(R2.id.fl_scene)
    FrameLayout flScene;
    @BindView(R2.id.iv_my_answer_0)
    ImageView ivMyAnswer0;
    @BindView(R2.id.iv_my_answer_1)
    ImageView ivMyAnswer1;
    @BindView(R2.id.iv_my_answer_2)
    ImageView ivMyAnswer2;
    @BindView(R2.id.iv_audio_play_or_pause)
    ImageView ivAudioPlayOrPause;
    @BindView(R2.id.tv_num_start_end)
    TextView tvNumStartEnd;
    @BindView(R2.id.tv_audio_time)
    TextView tvAudioTime;
    @BindView(R2.id.ll_audio)
    LinearLayout llAudio;
    @BindView(R2.id.scroll_view)
    ScrollView scrollView;
    @BindView(R2.id.ll_content)
    LinearLayout llContent;
    @BindView(R2.id.ll_layout)
    LinearLayout llLayout;
    @BindView(R2.id.tv_subject_tip)
    AppCompatTextView tvSubjectTip;
    @BindView(R2.id.ll_bottom)
    ConstraintLayout llBottom;
    @BindView(R2.id.ll_msg_tip)
    LinearLayout llMsgTip;
    @BindView(R2.id.tv_msg)
    TextView tvMsg;


    private int mMoudle;

    @Autowired(name = "examName")
    String mExamName;

    @Autowired(name = "examId")
    int mExamId;

    @Autowired(name = "publishId")
    int mPublishId;

    @Autowired(name = "studentExamId")
    int mStudentExamId;

    @Autowired(name = "fromPath")
    String mFromPath;

    @Autowired(name = "roomId")
    String mRoomId;

    @Autowired(name = "isLine")
    int mIsLine;

    @Autowired(name = "joinRoom")
    boolean mJoinRoom;

    @Autowired
    boolean mIsTupu = false;

    private boolean isFromRoom;

    private Long mAssistantExamId;

    private String mStudentId;

    private int mQuestionHeight;

    private int mCurrIndex = 0;
    private List<StudentExamQuestion> mQuestionList;
    private StudentExamQuestion mQuestionCurr;

    private PagePictureOnline mCurPagePictureOnLine; //不准，经常为null

    private Bitmap doodle_bitmap;
    private String picClipPath; //本地切图路径
    private String picFilePath;
    private float m_tran_x = -20f;
    private float m_tran_y = 0f;
    private float mTemp_x = 0f; //暂存转换后的坐标
    private float mTemp_y = 0f;
    private float mTemp_w = 0f; //暂存转换后的坐标
    private float mTemp_h = 0f;
    private int mPic_w = 2149;//1075 * 3 / 2;
    private int mPic_h = 3023;//* 3 / 2;
    private int fl_width;  //界面宽
    private int fl_height; //界面高

    private IDoodle mDoodle;
    private DoodleView mDoodleView;
    private DoodleParams mDoodleParams;
    private DoodleOnTouchGestureListener mTouchGestureListener;

    private PlayService playService;
    private PlayService.PlayBinder playBinder;
    private String audioPath;
    private int mDuration;  // 音频总时长
    private Animation scanAnim;

    //记录笔迹最小高度
    private volatile Float mMin_h = 0f;
    //记录笔迹最大高度
    private volatile Float mMax_h = 0f;
    //保存图片时，要截图，上下都多上这么多个像素
    private float mTran_h = 20f;


    private Map<String, String> mAnswerMap = new HashMap<>();
    private Map<Integer, Integer> mTimerMap = new HashMap<>(); //小题时长
    private volatile int secondRecord = 0; //记录时间

    private int sceneIndex = 0;
    private boolean mIsLoadImg_b_end = false;

    private int mDoodleSaveType = 0;
    private static final int DOODLE_SAVE_TYPE = 100; //当前点阵作答, 切换题目前保存当前作答
    private static final int DOODLE_SAVE_SCENCE_TYPE = 105; //当前点阵作答, 切换情景时
    private static final int DOODLE_SAVE_TYPE_SWITCH = 101; //当前点阵作答,切换纸张前保存当前作答
    private static final int DOODLE_SAVE_TYPE_ADD = 102; //当前点阵作答,切换纸张前保存当前作答

    private static final int DOODLE_SAVE_TYPE_SUBMIT = 103;//当前点阵作答,提交作业前保存当前作答
    private static final int DOODLE_SAVE_TYPE_SUBMIT_FORCE = 104;//当前点阵作答,随堂小测强制提交作业
    private static final int DOODLE_SAVE_TYPE_EXIT = 106;//当前点阵作答,退出作业页面前保存当前作答


    @Override
    public int getLayoutId() {
        return R.layout.homework_line_activity;
    }

    @Override
    public boolean getIsBindTsdService() {
        return true;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return mTsdListener;
    }

    @Override
    public HomeworkLineActivityPre createPresenter() {
        return new HomeworkLineActivityPre(this);
    }

    @Override
    public HomeworkLineActivityCon.View createView() {
        return this;
    }


    @Override
    public void init() {
        //禁止息屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        ////CodeProcessor.init(this);
        ////AjLatexMath.init(this);

        mStudentId = SPUtils.getInstance().getString(Constants.USER_ID_KEY);

        tabScene.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (null == mQuestionCurr) return;

                int newIndex = (int) tab.getTag();

                if (1 == sceneIndex && newIndex != sceneIndex) {
                    if (QuestionTypeUtil.isSubjectQuestion(mQuestionCurr.getQuestionType())
                            && null != mCurPagePictureOnLine && null != mDoodleView) {
                        llMsgTip.setVisibility(View.VISIBLE);
                        tvMsg.setText("正在切换中...");
                        sceneIndex = newIndex;
                        mDoodleSaveType = DOODLE_SAVE_SCENCE_TYPE;
                        mDoodleView.save();
                        return;
                    }
                }

                sceneIndex = newIndex;

                sceneQuestionSwitch(sceneIndex, mQuestionCurr);
                displaySceneByType(sceneIndex, mQuestionCurr);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        tabScene.addTab(tabScene.newTab().setCustomView(getTabTextView(this.getResources().getString(R.string.homework_scene_str))).setTag(0));
        tabScene.addTab(tabScene.newTab().setCustomView(getTabTextView(this.getResources().getString(R.string.homework_scene_question))).setTag(1));

        btNextSubmit.setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                if (null == mQuestionList) {
                    return;
                }
                int i = tabNum.getSelectedTabPosition();
                if (i >= mQuestionList.size() - 1) {
                    i = mQuestionList.size() - 1;
                    if (QuestionTypeUtil.isSubjectQuestion(mQuestionCurr.getQuestionType())
                            && null != mCurPagePictureOnLine && null != mDoodleView) {
                        btNextSubmit.setClickable(false);
                        //  DialogXUtil.waitDialogShow("正在保存...");;
                        tvMsg.setText("正在保存...");
                        llMsgTip.setVisibility(View.VISIBLE);
                        mDoodleSaveType = DOODLE_SAVE_TYPE_SUBMIT;
                        mDoodleView.save();
                    } else {
                        endTimer();
                        submitHomework();
                    }
                } else {
                    //网络极限情况下会导致提交标志为true，切换将标记改为false
                    if (mIsSubmiting){
                        mIsSubmiting = false;
                    }
                    tabNum.getTabAt(++i).select();
                }
            }
        });

        ivClose.setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                endTimer();
                for (Map.Entry<Integer, Integer> entry : mTimerMap.entrySet()) {
                    LogUtils.i("mTimerMap:" + "key=" + entry.getKey() + ",value=" + entry.getValue());
                }
                exitActivity();
            }
        });

        ivAudioPlayOrPause.setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                audioPlayOrPause();
            }
        });

        tvTitle.setText(StringUtil.replaceAmp(mExamName));

        llContent.post(new Runnable() {
            @Override
            public void run() {
                int t = llContent.getTop();
                int l = llContent.getLeft();
                int w = llContent.getWidth();
                int h = llContent.getHeight();
                LogUtils.i("onsize llContent t = " + t + " l = " + l + " w = " + w + " h = " + h);
            }
        });

        initPlayService();

        if (ConstantArouter.PATH_CLASSIN_MAINROOMACTIVITY.equals(mFromPath)) {
            isFromRoom = true;
            getPresenter().queryClassroomTestQuestionList(ComUtil.getHashmapByStr(
                    new String[]{"examPublishId"},
                    new String[]{mPublishId + ""}), true, false);
        } else {
            if (mIsTupu) {
                getPresenter().courseExamQuestionList((HashMap<String, Object>) ComUtil.getHashmapByStr(
                        new String[]{"examId"}, new Object[]{mExamId}), true, false);
            } else {
                getPresenter().getQuestionList((HashMap<String, Object>) ComUtil.getHashmapByStr(
                        new String[]{"examPublishId", "studentExamId"}, new Object[]{mPublishId, mStudentExamId}), true, false);
            }
        }
    }


    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        exitActivity();
    }

    private void exitActivity() {
        if (null != mQuestionCurr && QuestionTypeUtil.isSubjectQuestion(mQuestionCurr.getQuestionType())
                && null != mCurPagePictureOnLine && null != mDoodleView) {
            //DialogXUtil.waitDialogShow("正在保存...");
            llMsgTip.setVisibility(View.VISIBLE);
            tvMsg.setText("正在保存...");
            mDoodleSaveType = DOODLE_SAVE_TYPE_EXIT;
            mDoodleView.save();
        } else {
            if (!isFromRoom) {
                int emptyNum = 0;
                for (Map.Entry<String, String> entry : mAnswerMap.entrySet()) {
                    if (TextUtils.isEmpty(entry.getValue())) {
                        ++emptyNum;
                    }
                }
                AssistantExamOnline examOnline = DBUtils.getInstance(HomeworkLineActivity.this).getAssistantExamOnlineByPublishId(mPublishId, mExamId, mStudentId);
                if (null != examOnline) {
                    examOnline.setDealNum(examOnline.getTotalNum() - emptyNum);
                    examOnline.setTempAnswer(JsonUtils.toJson(mAnswerMap));
                    examOnline.setTempTimer(JsonUtils.toJson(mTimerMap));
                    DBUtils.getInstance(HomeworkLineActivity.this).updateAssistantExamOnline(examOnline);
                }
                EventBus.getDefault().postSticky(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_ANSWER_PROGRESS,
                        mExamId + "###" + mPublishId + "###" + (null != examOnline ? examOnline.getTotalNum() - emptyNum : 0)));
                finish();
                LogUtils.i("mAnswerMap:" + JsonUtils.toJson(mAnswerMap));
            } else {
                DialogXUtil.customDialogShow("您将放弃本次作答，是否确定退出？",
                        getResources().getString(R.string.ok), getResources().getString(R.string.cancel), false, new DialogXUtil.OnDialogXListen() {
                            @Override
                            public void onListenDialogOk() {
                                EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_BACK_FINISH, null));
                                clearAnswerRecord();
                                finish();
                            }

                            @Override
                            public void onListenDialogCancel() {
                            }

                            @Override
                            public void onListenDialogClose() {
                            }
                        });
            }
        }
    }


    /****************************提交*************************/
    private void submitHomework() {
        if (mIsSubmiting) {
            LogUtils.i(" mIsSubmiting == true  正在提交中...");
            return;
        }

        int emptyNum = 0;
        for (Map.Entry<String, String> entry : mAnswerMap.entrySet()) {
            if (TextUtils.isEmpty(entry.getValue())) {
                ++emptyNum;
            }
        }
        String content = 0 == emptyNum ? getResources().getString(R.string.homework_submit_question_tip) :
                String.format(getResources().getString(R.string.homework_submit_question_empty), emptyNum);
        DialogXUtil.customDialogShow(content,
                getResources().getString(R.string.homework_submit_button), getResources().getString(R.string.cancel), false, new DialogXUtil.OnDialogXListen() {
                    @Override
                    public void onListenDialogOk() {
                        mIsSubmiting = true;
                        exceptionSubmitCount = 0;
                        submitHomeworkOk();
                    }

                    @Override
                    public void onListenDialogCancel() {
                        startTimer();
                        mIsSubmiting = false;
                    }

                    @Override
                    public void onListenDialogClose() {
                        mIsSubmiting = false;
                        startTimer();
                    }
                });
    }

    private int exceptionSubmitCount = 0;

    private void submitHomeworkOk() {
        if (!ComUtil.isNetworkConnected()) {
            mIsSubmiting = false;
            ToastUtil.initToast(getString(R.string.network_disconnect_error));
            return;
        }

        //课堂互动时，检查直播间是否连接正常
        if (isFromRoom && !mJoinRoom) {
            mIsSubmiting = false;
            ToastUtil.initToast(getString(R.string.network_disconnect_error));
            return;
        }

        List<String> emptyNetList = null;
        for (Map.Entry<String, String> entry : mAnswerMap.entrySet()) {
            String questionInfo = entry.getKey();
            String[] quest = questionInfo.split("###");
            if (QuestionTypeUtil.isSubjectQuestion(Integer.parseInt(quest[1]))
                    && !TextUtils.isEmpty(entry.getValue())) {
                String[] tmp = entry.getValue().split("###");
                for (int k = 0; k < tmp.length; k++) {
                    PagePictureOnline pagePicture = DBUtils.getInstance(HomeworkLineActivity.this)
                            .getPagePictureOnlineByPictureLocal(tmp[k]);
                    if (null != pagePicture) {
                        if (TextUtils.isEmpty(pagePicture.getPictureUrl())
                                && new File(pagePicture.getLocalPath()).exists()) {
                            if (null == emptyNetList) {
                                emptyNetList = new ArrayList<>();
                            }
                            emptyNetList.add(pagePicture.getLocalPath());
                        }
                    }
                }
            }
        }

        //当前有作答图盘不存在上传图片地址,递归上传图片,上传完后再提交
        if (null != emptyNetList && emptyNetList.size() > 0 && exceptionSubmitCount < 3) {
            mIsSubmiting = false;
            exceptionSubmitCount++;
            uploadSubmit(emptyNetList);
            return;
        }

        if (null != emptyNetList) {
            LogUtils.e("emptyNetList " + GsonUtil.GsonString(emptyNetList) + " exceptionSubmitCount = " + exceptionSubmitCount);
        }

        exceptionSubmitCount = 0;
        if (null == mQuestionList || mQuestionList.size() == 0) {
            mIsSubmiting = false;
            return;
        }

        LogUtils.i("mAnswerMap " + mAnswerMap.toString());
        List<CommitAssistantQuestionsReq_vo> answerList = new ArrayList<>();
        for (Map.Entry<String, String> entry : mAnswerMap.entrySet()) {
            for (int j = 0; j < mQuestionList.size(); j++) {
                StudentExamQuestion question = mQuestionList.get(j);
                if (entry.getKey().equals(question.getQuestionId() + "###" + question.getQuestionType())
                        && !TextUtils.isEmpty(entry.getValue())) {
                    if (QuestionTypeUtil.isObjectQuestion(question.getQuestionType())) {
                        CommitAssistantQuestionsReq_vo answer = new CommitAssistantQuestionsReq_vo();
                        answer.setQuestionId(question.getQuestionId());
                        answer.setQuestionType(question.getQuestionType());
                        answer.setAnswerType(1);
                        answer.setAnswerContent(entry.getValue());
                        answer.setCommitTime(mTimerMap.get(j));
                        answerList.add(answer);
                    } else {
                        CommitAssistantQuestionsReq_vo answer = new CommitAssistantQuestionsReq_vo();
                        answer.setQuestionId(question.getQuestionId());
                        answer.setQuestionType(question.getQuestionType());
                        answer.setAnswerType(2);
                        answer.setCommitTime(mTimerMap.get(j));
                        String picUrls = getPicUrls(entry.getValue(), emptyNetList);
                        LogUtils.d("picUrls = " + picUrls);
                        /*if (TextUtils.isEmpty(picUrls))
                            return;*/
                        answer.setAnswerContent(picUrls);
                        answerList.add(answer);
                    }
                }
            }
        }

        AssistantExamOnline examOnline = DBUtils.getInstance(HomeworkLineActivity.this).getAssistantExamOnlineByPublishId(mPublishId, mExamId, mStudentId);

        CommitAssistantQuestionsOnlineReq req = new CommitAssistantQuestionsOnlineReq();
        if (mIsTupu) {

        } else {
            req.setPublishId(mPublishId);
        }
        if (isFromRoom) {
            req.setRoomId(mRoomId);
            req.setIsLine(mIsLine);
            req.setPageVos(null);
            req.setId(SPUtils.getInstance().getString(Constants.USER_ID_KEY));
            req.setInstructions("studentCommitExam");
            req.setExamId(mExamId);
        } else {
            req.setStudentId(SPUtils.getInstance().getString(Constants.USER_ID_KEY));
            req.setStudentExamId(mStudentExamId);
        }
        req.setQuestionList(answerList);
        req.setBeginTime(null != examOnline ? examOnline.getBeginTime() : null);
        req.setFinishTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));

        if (isFromRoom) {
            EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_WEBSOCKE_SMALLTEST_COMMIT, JsonUtils.toJson(req)));
            mTsdServiceBinder.on_setmModule(TsdService.MODULE_ROOM);
            // DialogXUtil.waitDialogShow("正在提交作业...");
            llMsgTip.setVisibility(View.VISIBLE);
            tvMsg.setText("正在提交作业...");
        } else {
            getPresenter().getCommitAnswer(GsonUtil.GsonString(req), true, "正在提交考试...", false);
        }
    }


    private String getPicUrls(String str, List<String> exceptList) {
        String[] tmp = str.split("###");
        StringBuilder sb = new StringBuilder();

        // List<String> exceptionPath = null;
        for (int k = 0; k < tmp.length; k++) {
            if (null != exceptList && exceptList.contains(tmp[k])) continue;

            PagePictureOnline pagePicture = DBUtils.getInstance(HomeworkLineActivity.this)
                    .getPagePictureOnlineByPictureLocal(tmp[k]);
            if (null != pagePicture && !TextUtils.isEmpty(pagePicture.getPictureUrl())) {
                sb.append(pagePicture.getPictureUrl());
                if (k != tmp.length - 1) {
                    sb.append(",");
                }
            }
        }

        return sb.toString();
    }

    private void uploadSubmit(List<String> exceptionPath) {
        upload(exceptionPath, 0, new OnListenProcess() {
            @Override
            public void onListenStart() {
                initDialog(HomeworkLineActivity.this);
                setDialogContent("正在同步作答...");
            }

            @Override
            public void onListenEnd(String uploadFile, String localFile, List<String> list, int index, OnListenProcess onListenProcess) {
                PagePictureOnline pagePictureOnline = DBUtils.getInstance(HomeworkLineActivity.this)
                        .getPagePictureOnlineByPictureLocalClip(localFile);
                if (null != pagePictureOnline) {
                    LogUtils.i(localFile + " : " + uploadFile);
                    pagePictureOnline.setPictureUrl(uploadFile);
                    DBUtils.getInstance(HomeworkLineActivity.this).updatePagePictureOnline(pagePictureOnline);
                }

                upload(list, index, onListenProcess);
            }

            @Override
            public void onListenError(List<String> list, int index, OnListenProcess onListenProcess) {
                upload(list, index, onListenProcess);
            }

            @Override
            public void onListenAllEnd() {
                dissDialog();
                mIsSubmiting = true;
                submitHomeworkOk();
            }

            private Dialog mDialog;
            private TextView tvTip;

            private void initDialog(Context activity) {
                dissDialog();
                mDialog = new Dialog(activity, R.style.ActionSheetDialogStyle);
                mDialog.setCanceledOnTouchOutside(false);
                mDialog.setContentView(R.layout.dialog_wait);
                Window window = mDialog.getWindow();
                WindowManager.LayoutParams lp = window.getAttributes();
                window.setGravity(Gravity.CENTER);
//                lp.x = 0; // 新位置X坐标
//                lp.y = 0; // 新位置Y坐标
//                lp.width = 400; // 400宽度
//                lp.height = 350; // 350高度
                //               lp.alpha = 0.8f; // 透明度
                window.setAttributes(lp);
                mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        return keyCode == KeyEvent.KEYCODE_BACK;
                    }
                });
                tvTip = mDialog.findViewById(R.id.tv_msg);
            }

            public void setDialogContent(String content) {
                if (!TextUtils.isEmpty(content)) {
                    tvTip.setText(content);
                } else {
                    tvTip.setText("请稍后，正在下载中...");
                }

                if (mDialog != null && !mDialog.isShowing()) {
                    mDialog.show();
                }
            }

            public void dissDialog() {
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
            }
        });
    }


    public interface OnListenProcess {
        void onListenStart();

        void onListenEnd(String uploadFile, String localFile, List<String> list, int index, OnListenProcess onListenProcess);

        void onListenError(List<String> list, int index, OnListenProcess onListenProcess);

        void onListenAllEnd();
    }


    private synchronized void upload(final List<String> list, final int index, final OnListenProcess onListenProcess) {
        LogUtils.i("upload index = " + index + " size = " + list.size());
        if (index >= list.size()) {
            if (null != onListenProcess) {
                onListenProcess.onListenAllEnd();
            }
            return;
        }

        LogUtils.i("upload 002");
        final String temp = list.get(index);
        if (TextUtils.isEmpty(temp) || !new File(temp).exists()) {
            if (null != onListenProcess) {
                onListenProcess.onListenError(list, index + 1, onListenProcess);
            }
            return;
        }

        if (0 == index && null != onListenProcess) {
            onListenProcess.onListenStart();
        }
        //这里保存的是原始图路径，需要转换成切图路径上传
        String clipPath = temp.substring(0, temp.lastIndexOf(".")) + "clip" + ".png";
        StringBuilder uploadFile = new StringBuilder();
        uploadFile.append(FileUtils.getFileNameNoExtension(clipPath));
        uploadFile.append("_");
        uploadFile.append(new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS").format(System.currentTimeMillis()));
        uploadFile.append(".png");
        LogUtils.i(temp + " : " + uploadFile.toString());
        UploadOss.getInstance().upload2OSS(uploadFile.toString(), clipPath, new UploadOss.OnUploadListener() {
            @Override
            public String uploadSuccess(String uploadFile, String localFile, OssParams ossParams) {
                if (null != onListenProcess) {
                    onListenProcess.onListenEnd(uploadFile, localFile, list, index + 1, onListenProcess);
                }
                return null;
            }

            @Override
            public String uploadFail(String uploadFile, String localFile, OssParams ossParams) {
                if (null != onListenProcess) {
                    onListenProcess.onListenError(list, index + 1, onListenProcess);
                }
                return null;
            }
        }, null);
    }


    /****************************播放*************************/

    private void initPlayService() {
        Intent playService = new Intent(this, PlayService.class);
        this.bindService(playService, playConnection, Service.BIND_AUTO_CREATE);
    }

    private void audioPlayOrPause() {
        String url = mQuestionCurr.getListeningUrl();

        if (playBinder != null) {
            if (audioPath == null || !audioPath.equals(url)) {
                if (url != null) {
                    mDuration = 0;
                    setPlayMusicUrl(url);
                }
                if (null == scanAnim) {
                    scanAnim = AnimationUtils.loadAnimation(this, R.anim.common_dialog_rotate);
                    scanAnim.setInterpolator(new LinearInterpolator());
                }
                ivAudioPlayOrPause.startAnimation(scanAnim);
                ivAudioPlayOrPause.setClickable(false);
                //ivAudioPlayOrPause.setVisibility(View.INVISIBLE);
            } else if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PLAY) {
                //暂停
                playBinder.callPauseMusic();
                //ivAudioPlayOrPause.setVisibility(View.VISIBLE);
            } else if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PAUSE) {
                //恢复
                playBinder.callResumeMusic();
                // ivAudioPlayOrPause.setVisibility(View.VISIBLE);
            } else if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_STOP) {

                //ivAudioPlayOrPause.setVisibility(View.VISIBLE);
            } else if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_COMPLETE) {
                playBinder.callPlayMusic();
                // ivAudioPlayOrPause.setVisibility(View.VISIBLE);
            }
        }
        audioPath = url;
    }

    private void setPlayMusicUrl(String url) {
        if (playBinder != null) {
            playBinder.callSetmUrl(url);
        }
    }

    private ServiceConnection playConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            playBinder = (PlayService.PlayBinder) service;
            playService = playBinder.getService();
            playService.setCallback(new PlayService.CallbackPlay() {
                @Override
                public void onDataTestChange(String data) {

                }

                @Override
                public void onMusicStausChange(int status) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ivAudioPlayOrPause.clearAnimation();
                            if (scanAnim != null) {
                                scanAnim.cancel();
                                scanAnim = null;
                            }
                            ivAudioPlayOrPause.setClickable(true);
                            if (status == PlayService.STATUS_MUSIC_PLAY) {
                                ivAudioPlayOrPause.setImageResource(R.drawable.homework_icon_pause);
                            } else {
                                ivAudioPlayOrPause.setImageResource(R.drawable.homework_icon_play);
                            }
                        }
                    });
                }

                @Override
                public void onCurrentPosition(int currentPosition, int duration) {
                    runOnUiThread(() -> {
                        if (duration > 0 && currentPosition <= duration) {
                            if (mDuration == 0 && duration != 0) {
                                mDuration = duration;
                            } else if (mDuration != 0) {
                            }
                            updateCurrentTime(currentPosition, duration);
                        }
                    });
                }

                @Override
                public void onCompletion() {

                }

                @Override
                public void OnDuration(int duration) {

                }

                @Override
                public void onLoadedUrl() {
                    if (playBinder != null) {
                        playBinder.callPlayMusic();
                    }
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    private void updateCurrentTime(int cur, int duration) {
        String audioTime;
        if (duration < 0 || cur == 0) {
            audioTime = String.format("%s/%s", "00:00", ComUtil.strToTime(duration / 1000 + ""));
        } else {
            audioTime = String.format("%s/%s", ComUtil.strToTime(cur / 1000 + ""), ComUtil.strToTime(duration / 1000 + ""));
        }
        tvAudioTime.setText(audioTime);
    }


    @Override
    protected void onStop() {
        super.onStop();
        if (null != playBinder) {
            playBinder.callPauseMusic();
        }
    }

    @Override
    protected void onDestroy() {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        if (mIsTupu) {
            EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_LINE_TUPU_OUT, null));
        }
        super.onDestroy();
        setTsdServiceDisConnect();
        if (playConnection != null) {
            unbindService(playConnection);
            playConnection = null;
        }
        if(playBinder != null) {
            playBinder = null;
        }
        if(playService != null) {
            playService.setCallback(null);
            playService = null;
        }

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }

        DialogXUtil.dismissAll();

        mHandler.removeCallbacksAndMessages(null);
    }


    @Override
    public void getQuestionListResult(BaseResponse<QueryExamQuestionsResponse> response) {
        if (null == response) return;

        QueryExamQuestionsResponse data = response.getData();
        if (mIsTupu) {
            mStudentExamId = data.getStudentExamId();
        }
        if (null == data) return;

        mQuestionList = data.getQuestionList();
        if (null == mQuestionList || 0 == mQuestionList.size()) return;

        setAssistantExamId(mQuestionList.size());
        setQuestionAnswer(mQuestionList);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                display(mQuestionList);
                if (mIsTupu) {
                    EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_LINE_TUPU_INTO, null));
                }
            }
        });

    }

    /************************************题干显示************************************/

    private synchronized void display(List<StudentExamQuestion> questionList) {
        mQuestionCurr = questionList.get(mCurrIndex);
        if (null == mQuestionCurr) return;

        tabNum.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (null == mQuestionList) return;

                if (mCurrIndex != (int) tab.getTag()) {
                    endTimer();
                }
                if (!TextUtils.isEmpty(mAnswerMap.get(mQuestionCurr.getQuestionId() + "###" + mQuestionCurr.getQuestionType()))) {
                    ((TextView) tabNum.getTabAt(mCurrIndex).getCustomView()).setTextColor(getResources().getColor(R.color.colorText));
                } else {
                    ((TextView) tabNum.getTabAt(mCurrIndex).getCustomView()).setTextColor(Color.BLACK);
                }

                mCurrIndex = (int) tab.getTag();

                ((TextView) tabNum.getTabAt(mCurrIndex).getCustomView()).setTextColor(Color.WHITE);

                if (mCurrIndex >= mQuestionList.size() - 1) {
                    mCurrIndex = mQuestionList.size() - 1;
                    btNextSubmit.setText(getResources().getString(R.string.homework_submit_tip));
                } else {
                    btNextSubmit.setText(getResources().getString(R.string.homework_next_tip));
                }

                if (QuestionTypeUtil.isSubjectQuestion(mQuestionCurr.getQuestionType())
                        && null != mCurPagePictureOnLine && null != mDoodleView) {//
                    //DialogXUtil.waitDialogShow("正在切换中...");
                    tvMsg.setText("正在切换中...");
                    llMsgTip.setVisibility(View.VISIBLE);

                    mDoodleSaveType = DOODLE_SAVE_TYPE;
                    mDoodleView.save();
                    return;
                }

                startTimer();
                refreshByQuestion(mQuestionCurr = mQuestionList.get(mCurrIndex));
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        for (int i = 0; i < questionList.size(); i++) {
            StudentExamQuestion item = questionList.get(i);
            if (null == item || null == item.getQuestionNo()) continue;

            View inflate = View.inflate(this, R.layout.homework_tab_view, null);
            TextView tv = inflate.findViewById(R.id.tv_tabName);
            tv.setText(item.getQuestionNo().toString());
            if (i == mCurrIndex) {
                tv.setTextColor(Color.WHITE);
            } else {
                if (!TextUtils.isEmpty(mAnswerMap.get(item.getQuestionId() + "###" + item.getQuestionType()))) {
                    tv.setTextColor(getResources().getColor(R.color.colorText));
                } else {
                    tv.setTextColor(Color.BLACK);
                }
            }
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) tv.getLayoutParams();
            layoutParams.rightMargin = 5;
            layoutParams.leftMargin = 5;
            tv.setLayoutParams(layoutParams);
            tabNum.addTab(tabNum.newTab().setCustomView(tv).setTag(i), false);
        }

        tabNum.getTabAt(mCurrIndex).select();
        tabNum.postDelayed(new Runnable() {
            @Override
            public void run() {
                //tabNum.getTabAt(mCurrIndex).select();
                tabNum.setScrollPosition(0, mCurrIndex, true);
            }
        }, 300);


        refreshByQuestion(mQuestionCurr);

    }

    private void setQuestionAnswer(List<StudentExamQuestion> questionList) {
        int firstEmptyIndex = -1;
        for (int i = 0; i < questionList.size(); i++) {
            StudentExamQuestion item = questionList.get(i);
            if (null != item) {
                if (QuestionTypeUtil.isObjectQuestion(item.getQuestionType())) {
                    AssistantQuestionOnline answer = DBUtils.getInstance(this)
                            .getAssistantQuestionOnlineByQuestionId(mAssistantExamId, item.getQuestionId());
                    if (null != answer && !TextUtils.isEmpty(answer.getMyAnswer()) && !isFromRoom) {
                        mAnswerMap.put(item.getQuestionId() + "###" + item.getQuestionType(), answer.getMyAnswer());
                    } else {
                        mAnswerMap.put(item.getQuestionId() + "###" + item.getQuestionType(), "");

                        if (-1 == firstEmptyIndex) {
                            firstEmptyIndex = i;
                        }
                    }
                } else {
                    List<PagePictureOnline> listPicture = DBUtils.getInstance(this)
                            .getPagePicturesByQuestionId(mAssistantExamId, item.getQuestionId());
                    if (null != listPicture && listPicture.size() > 0 && !isFromRoom) {
                        StringBuilder sb = new StringBuilder();
                        for (int j = 0; j < listPicture.size(); j++) {
                            PagePictureOnline item1 = listPicture.get(j);
                            if (null != item1) {
                                LogUtils.i("i=" + j + " PagePictureOnline " + item1.toString());
                                if (!TextUtils.isEmpty(item1.getLocalPath())
                                        && new File(item1.getLocalPath()).exists()) {
                                    sb.append(item1.getLocalPath());
                                    if (j != listPicture.size() - 1) {
                                        sb.append("###");
                                    }
                                } else {
                                    LogUtils.e("item1.getLocalPath() = " + item1.getLocalPath() + " is null or not exist");
                                }
                            }
                        }
                        mAnswerMap.put(item.getQuestionId() + "###" + item.getQuestionType(), sb.toString());
                    } else {
                        mAnswerMap.put(item.getQuestionId() + "###" + item.getQuestionType(), "");
                        if (-1 == firstEmptyIndex) {
                            firstEmptyIndex = i;
                        }
                    }
                }
            }
        }

        mCurrIndex = -1 == firstEmptyIndex ? 0 : firstEmptyIndex;

        int emptyNum = 0;
        for (Map.Entry<String, String> entry : mAnswerMap.entrySet()) {
            if (TextUtils.isEmpty(entry.getValue())) {
                ++emptyNum;
            }
        }
        AssistantExamOnline examOnline = DBUtils.getInstance(this).getAssistantExamOnlineByPublishId(mPublishId, mExamId, mStudentId);
        if (null == examOnline) {
            examOnline = new AssistantExamOnline(null,
                    mPublishId, mExamName, mExamId,
                    SPUtils.getInstance().getString(Constants.USER_ID_KEY),
                    ComUtil.getStringDate(), "",
                    questionList.size(), questionList.size() - emptyNum, JsonUtils.toJson(mAnswerMap), JsonUtils.toJson(mTimerMap));
            DBUtils.getInstance(this).insertAssistantExamOnline(examOnline);
            DBUtils.getInstance(this).clearBuffer();
        } else {
            if (examOnline.getTempTimer() != null) {
                mTimerMap = JsonUtils.fromJson(examOnline.getTempTimer(),
                        new TypeToken<HashMap<Integer, Integer>>() {
                        }.getType());
            }
            examOnline.setDealNum(examOnline.getTotalNum() - emptyNum);
            examOnline.setTempAnswer(JsonUtils.toJson(mAnswerMap));
            examOnline.setTempTimer(JsonUtils.toJson(mTimerMap));
            DBUtils.getInstance(this).updateAssistantExamOnline(examOnline);
        }

        LogUtils.i("mTimerMap:" + JsonUtils.toJson(mTimerMap));
    }

    private void refreshByQuestion(StudentExamQuestion question) {
        updatePageLayout(question);
    }

    private void displayQuestionInfo(StudentExamQuestion question) {
        switch (question.getQuestionType()) {
            case QuestionType.QUESTIONTYPE_DANXUANTI://单选题
            case QuestionType.QUESTIONTYPE_WENZONGXUANZETI://文综选择题
            case QuestionType.QUESTIONTYPE_YINYUXUANZETI://英语选择题
            case QuestionType.QUESTIONTYPE_TINGLIXUANZETI://听力选择
            {
                LogUtils.d("question " + question.toString());
                tvSubjectTip.setVisibility(View.INVISIBLE);
                QuestionUtils.visualSingleChoiceContent(HomeworkLineActivity.this, llQuestion, llQuestionAnswer, question, mAnswerMap.get(question.getQuestionId() + "###" + mQuestionCurr.getQuestionType()), new QuestionUtils.OnChoiceListener() {
                    @Override
                    public void onListener(String tempAnswer, String answer, StudentExamQuestion question) {
                        updateQuestionAnswer(tempAnswer, answer, question);
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                int tempIndex = mCurrIndex;
                                if (tempIndex < mQuestionList.size() - 1) {
                                    tabNum.getTabAt(++tempIndex).select();
                                }
                            }
                        }, 500);
                    }
                });
                mCurPagePictureOnLine = null;
            }
            break;
            case QuestionType.QUESTIONTYPE_DUOXUANTI: {
                tvSubjectTip.setVisibility(View.INVISIBLE);
                QuestionUtils.visualMultiChoiceContent(HomeworkLineActivity.this, llQuestion, llQuestionAnswer, question, mAnswerMap.get(question.getQuestionId() + "###" + mQuestionCurr.getQuestionType()), new QuestionUtils.OnChoiceListener() {
                    @Override
                    public void onListener(String tempAnswer, String answer, StudentExamQuestion question) {
                        updateQuestionAnswer(tempAnswer, answer, question);
                    }
                });
                mCurPagePictureOnLine = null;
            }
            break;
            case QuestionType.QUESTIONTYPE_PANDUANTI: {
                tvSubjectTip.setVisibility(View.INVISIBLE);
                QuestionUtils.visualJudgeChoiceContent(HomeworkLineActivity.this, llQuestion, llQuestionAnswer, question, mAnswerMap.get(question.getQuestionId() + "###" + mQuestionCurr.getQuestionType()), new QuestionUtils.OnChoiceListener() {
                    @Override
                    public void onListener(String tempAnswer, String answer, StudentExamQuestion question) {
                        updateQuestionAnswer(tempAnswer, answer, question);
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                int tempIndex = mCurrIndex;
                                if (tempIndex < mQuestionList.size() - 1) {
                                    tabNum.getTabAt(++tempIndex).select();
                                }
                            }
                        }, 500);
                    }
                });
                mCurPagePictureOnLine = null;
            }
            break;
            case QuestionType.QUESTIONTYPE_TIANKONGTI://填空题
            case QuestionType.QUESTIONTYPE_JIANDATI://简答题
            case QuestionType.QUESTIONTYPE_XIEZUOTI://写作题
            case QuestionType.QUESTIONTYPE_TINGLITIANKONG://听力填空
            case QuestionType.QUESTIONTYPE_JIANDATI12://简答题12
            case QuestionType.QUESTIONTYPE_PINXIE://拼写
            {

                tvSubjectTip.setVisibility(View.VISIBLE);
                QuestionUtils.visualQuestionPenContent(HomeworkLineActivity.this, llQuestion, question, null);
                setSubjectQuestion(question);
                if (TsdService.M_BLE_DEVICE == null) {
                    showNotConnectPenDialog();
                }
            }
            break;
        }
    }


    private final Handler mHandler = new Handler();
    /**
     * 滚屏的线程
     */
    private Runnable ScrollRunnable = new Runnable() {

        @SuppressLint("NewApi")
        @Override
        public void run() {
            // TODO Auto-generated method stub
            int off = llLayout.getMeasuredHeight() - scrollView.getHeight();// 判断高度
            LogUtils.i(" onsize llLayout.getMeasuredHeight() = " + llLayout.getMeasuredHeight() + " scrollView.getHeight() = " + scrollView.getHeight());
            if (off > 0) {
                scrollView.scrollBy(0, 50);
                if (scrollView.getScaleY() == off) {
                    Thread.currentThread().interrupt();
                } else {
                    mHandler.postDelayed(this, 1000);
                }
            }
        }
    };

    private void showNotConnectPenDialog() {
        DialogXUtil.customDialogShow("您还未连接蓝牙笔,是否去连接？", new DialogXUtil.OnDialogXListen() {
            @Override
            public void onListenDialogOk() {
                ARouter.getInstance().build(ConstantArouter.PATH_PEN_PENMAINACTIVITY)
                        .navigation();
            }

            @Override
            public void onListenDialogCancel() {

            }

            @Override
            public void onListenDialogClose() {

            }
        });
    }

    private void displaySceneByType(int index, StudentExamQuestion question) {
        LogUtils.i(" <<<< index = " + index);
        if (0 == index) {
            // llQuestion.setText(question.getQuestionScreen());
            if (null == flScene.getChildAt(0)) {
                LinearLayout.LayoutParams lp0 = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                FlexibleRichTextView questionfrtv = new FlexibleRichTextView(this);
                questionfrtv.setText(TextUtils.isEmpty(question.getQuestionScreen()) ? "" : FormulaUtil.reLatex(question.getQuestionScreen()));
                flScene.addView(questionfrtv, lp0);
            } else {
                FlexibleRichTextView tempText = ((FlexibleRichTextView) flScene.getChildAt(0));
                tempText.resetTextView();
                tempText.setText(TextUtils.isEmpty(question.getQuestionScreen()) ? "" : FormulaUtil.reLatex(question.getQuestionScreen()));
            }
            tvSubjectTip.setVisibility(View.INVISIBLE);
        } else {
            displayQuestionInfo(question);
        }
        LogUtils.i(" >>>> index = " + index);
    }

    /**
     * 显示主观题
     *
     * @param question
     */
    private void setSubjectQuestion(StudentExamQuestion question) {
        mCurPagePictureOnLine = null;

        String pageStr = mAnswerMap.get(question.getQuestionId() + "###" + question.getQuestionType());
        if (TextUtils.isEmpty(pageStr)) {
            //llAnswer.setVisibility(View.GONE);
            ivMyAnswer0.setVisibility(View.GONE);
            ivMyAnswer1.setVisibility(View.GONE);
            ivMyAnswer2.setVisibility(View.GONE);
            return;
        }

        String[] pageArray = pageStr.split("###");

        if (pageArray == null) {
            ivMyAnswer0.setVisibility(View.GONE);
            ivMyAnswer1.setVisibility(View.GONE);
            ivMyAnswer2.setVisibility(View.GONE);
        } else {
            ivMyAnswer0.setVisibility(View.GONE);
            ivMyAnswer1.setVisibility(View.GONE);
            ivMyAnswer2.setVisibility(View.GONE);
            if (pageArray.length == 1) {
                LogUtils.i("questionId = " + question.getQuestionId() + "pageArray[0] = " + pageArray[0]);
                ivMyAnswer0.setVisibility(View.VISIBLE);
                loadIntoUseFitWidth(this, pageArray[0], ivMyAnswer0);
            } else if (pageArray.length == 2) {
                LogUtils.i("questionId = " + question.getQuestionId() + "pageArray[0] = " + pageArray[0]);
                LogUtils.i("questionId = " + question.getQuestionId() + "pageArray[1] = " + pageArray[1]);
                ivMyAnswer0.setVisibility(View.VISIBLE);
                ivMyAnswer1.setVisibility(View.VISIBLE);
                //Glide.with(this).asBitmap().load(pageArray[0]).signature(new ObjectKey(System.currentTimeMillis())).into(ivMyAnswer0);
                //Glide.with(this).asBitmap().load(pageArray[1]).signature(new ObjectKey(System.currentTimeMillis())).into(ivMyAnswer1);
                loadIntoUseFitWidth(this, pageArray[0], ivMyAnswer0);
                loadIntoUseFitWidth(this, pageArray[1], ivMyAnswer1);
            } else if (pageArray.length >= 3) {
                LogUtils.i("questionId = " + question.getQuestionId() + "pageArray[0] = " + pageArray[0]);
                LogUtils.i("questionId = " + question.getQuestionId() + "pageArray[1] = " + pageArray[1]);
                LogUtils.i("questionId = " + question.getQuestionId() + "pageArray[2] = " + pageArray[2]);
                ivMyAnswer0.setVisibility(View.VISIBLE);
                ivMyAnswer1.setVisibility(View.VISIBLE);
                ivMyAnswer2.setVisibility(View.VISIBLE);
//                Glide.with(this).asBitmap().load(pageArray[0]).signature(new ObjectKey(System.currentTimeMillis())).into(ivMyAnswer0);
//                Glide.with(this).asBitmap().load(pageArray[1]).signature(new ObjectKey(System.currentTimeMillis())).into(ivMyAnswer1);
//                Glide.with(this).asBitmap().load(pageArray[2]).signature(new ObjectKey(System.currentTimeMillis())).into(ivMyAnswer2);
                loadIntoUseFitWidth(this, pageArray[0], ivMyAnswer0);
                loadIntoUseFitWidth(this, pageArray[1], ivMyAnswer1);
                loadIntoUseFitWidth(this, pageArray[2], ivMyAnswer2);
            }
        }
    }

    public static void loadIntoUseFitWidth(Context context, final String imageUrl, final ImageView imageView) {
        /*Glide.with(context)
                .load(imageUrl)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable @org.jetbrains.annotations.Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        if (imageView == null) {
                            return false;
                        }
                        if (imageView.getScaleType() != ImageView.ScaleType.FIT_XY) {
                            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        }
                        ViewGroup.LayoutParams params = imageView.getLayoutParams();
                        int vw = imageView.getWidth() - imageView.getPaddingLeft() - imageView.getPaddingRight();
                        LogUtils.i("glide imageView.getWidth() = " + imageView.getWidth() + " imageView.getPaddingLeft() = " + imageView.getPaddingLeft());
                        LogUtils.i("glide imageView.getHeight() = " + imageView.getHeight() + " imageView.getPaddingRight() = " + imageView.getPaddingRight());
                        float scale = (float) vw / (float) resource.getIntrinsicWidth();
                        int vh = Math.round(resource.getIntrinsicHeight() * scale);
                        LogUtils.i("glide resource.getIntrinsicWidth() = " + resource.getIntrinsicWidth() + " resource.getIntrinsicHeight() = " + resource.getIntrinsicHeight());
                        LogUtils.i("glide scale = " + scale + " vw = " + vw + " vh = " + vh);
                        params.height = vh + imageView.getPaddingTop() + imageView.getPaddingBottom();
                        LogUtils.i("glide imageView.getPaddingTop() = " + imageView.getPaddingTop() + " imageView.getPaddingBottom() = " + imageView.getPaddingBottom());
                        LogUtils.i("glide params.height = " + params.height);
                        imageView.setLayoutParams(params);
                        return false;
                    }
                })
                .signature(new ObjectKey(System.currentTimeMillis()))
                .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                .into(imageView);*/
        Glide.with(context).asBitmap()
                .signature(new ObjectKey(System.currentTimeMillis()))
//                .override(2180, 2044)
                .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) //设置原始尺寸
                .load(imageUrl).into(imageView);
    }


    private void updatePageLayout(StudentExamQuestion question) {
        if (1 == question.getIsSingle()) {//单题
            tabScene.setVisibility(View.GONE);
            flScene.setVisibility(View.GONE);
            llQuestion.setVisibility(View.VISIBLE);
            if (QuestionTypeUtil.isObjectQuestion(question.getQuestionType())) {
                llQuestionAnswer.setVisibility(View.VISIBLE);
                flDoodle.setVisibility(View.GONE);
                ivMyAnswer0.setVisibility(View.GONE);
                ivMyAnswer1.setVisibility(View.GONE);
                ivMyAnswer2.setVisibility(View.GONE);
            } else {
                llQuestionAnswer.setVisibility(View.GONE);
                // llAnswer.setVisibility(View.VISIBLE);
                flDoodle.setVisibility(View.GONE);
            }
            llAudio.setVisibility(View.GONE);
            displayQuestionInfo(question);
        } else {//情景题
            tabScene.setVisibility(View.VISIBLE);
            if (1 == question.getScreenIsView()) {
                sceneIndex = 0;
                tabScene.getTabAt(0).select();
            } else {
                sceneIndex = 1;
                tabScene.getTabAt(1).select();
            }

            sceneQuestionSwitch(sceneIndex, question);
            displaySceneByType(question.getScreenIsView() - 1, question);
        }
    }

    private void sceneQuestionSwitch(int currIndex, StudentExamQuestion question) {
        if (0 == currIndex) {
            flScene.setVisibility(View.VISIBLE);
            llQuestion.setVisibility(View.GONE);
            llQuestionAnswer.setVisibility(View.GONE);
            flDoodle.setVisibility(View.GONE);
            ivMyAnswer0.setVisibility(View.GONE);
            ivMyAnswer1.setVisibility(View.GONE);
            ivMyAnswer2.setVisibility(View.GONE);
        } else {
            flScene.setVisibility(View.GONE);
            llQuestion.setVisibility(View.VISIBLE);
            if (QuestionTypeUtil.isObjectQuestion(question.getQuestionType())) {
                llQuestionAnswer.setVisibility(View.VISIBLE);
                flDoodle.setVisibility(View.GONE);
                ivMyAnswer0.setVisibility(View.GONE);
                ivMyAnswer1.setVisibility(View.GONE);
                ivMyAnswer2.setVisibility(View.GONE);
            } else {
                llQuestionAnswer.setVisibility(View.GONE);
                //llAnswer.setVisibility(View.VISIBLE);
                flDoodle.setVisibility(View.GONE);
            }
        }

        if (!TextUtils.isEmpty(question.getListeningUrl())
                && (question.getQuestionType() == QuestionType.QUESTIONTYPE_TINGLIXUANZETI
                || question.getQuestionType() == QuestionType.QUESTIONTYPE_TINGLITIANKONG)) {
            llAudio.setVisibility(View.VISIBLE);
        } else {
            llAudio.setVisibility(View.GONE);
        }

        if (View.VISIBLE == llAudio.getVisibility()) {
            LogUtils.i("llAudio visual  questionId = " + question.getQuestionId() + " type =" + question.getQuestionType());
            if (null != playService) {
                LogUtils.i("playService.getmUrl() = " + playService.getmUrl());
            } else {
                LogUtils.i("playService = null");
            }
            LogUtils.i("question.getListeningUrl() = " + question.getListeningUrl());
            if (!question.getListeningUrl().equals(null == playService ? null : playService.getmUrl())) {
                LogUtils.i("new audio url ");
                if (null != playService && playService.isPlaying()) {
                    playService.stopMusic();
                    playService.setmUrl(null);
                    audioPath = null;
                }
                tvAudioTime.setText(String.format("%s/%s", "00:00", ComUtil.intToTime(question.getDuration().intValue())));
                tvNumStartEnd.setText(String.format(getResources().getString(R.string.homework_audio_scope), question.getScreenBegin(), question.getScreenEnd()));
            }
        } else {
            if (null != playService && playService.isPlaying()) {
                playService.stopMusic();
                playService.setmUrl(null);
                audioPath = null;
            }
        }
    }


    private void updateQuestionAnswer(String tempAnswer, String answer, StudentExamQuestion question) {
        if (!TextUtils.isEmpty(tempAnswer) && tempAnswer.equalsIgnoreCase(answer)) {
            return;
        }

        mAnswerMap.put(question.getQuestionId() + "###" + question.getQuestionType(), answer);
        AssistantQuestionOnline assistantQuestionOnline = DBUtils.getInstance(this)
                .getAssistantQuestionOnlineByQuestionId(mAssistantExamId, question.getQuestionId());
        if (null == assistantQuestionOnline) {
            assistantQuestionOnline = new AssistantQuestionOnline(null, question.getQuestionId(), question.getQuestionNo(), question.getQuestionScore(),
                    question.getQuestionContent(), question.getQuestion(), StringUtil.strlistToString(question.getOptions(), "###"), question.getExplain(),
                    question.getAnswerContent(), question.getQuestionType(), question.getIsSingle(), question.getQuestionScreen(), question.getScreenType(),
                    question.getScreenId(), question.getListeningUrl(), question.getDuration(), question.getChapterId(),
                    question.getQuestionDetailId(), answer, null, mAssistantExamId);
            DBUtils.getInstance(this).insertAssistantQuestionOnline(assistantQuestionOnline);
        } else {
            assistantQuestionOnline.setMyAnswer(answer);
            DBUtils.getInstance(this).updateAssistantQuestionOnline(assistantQuestionOnline);
        }
    }

    private void setAssistantExamId(int total) {
        AssistantExamOnline assistantExam = DBUtils.getInstance(this).getAssistantExamOnlineByPublishId(mPublishId, mExamId, mStudentId);
        if (assistantExam == null) {
            mAssistantExamId = DBUtils.getInstance(this)
                    .insertAssistantExamOnline(new AssistantExamOnline(null, mPublishId, mExamName, mExamId, mStudentId, ComUtil.getStringDate(), null, total, 0, null, null));
            DBUtils.getInstance(this).clearBuffer();
        } else {
            mAssistantExamId = assistantExam.getId();
        }

    }


    private TextView getTabTextView(String str) {
        View inflate = View.inflate(this, R.layout.homework_tab_text_view, null);
        TextView tv = inflate.findViewById(R.id.tv_tabName_question);
        tv.setText(str);
        return tv;
    }


    /************************************藍牙筆和涂鸦************************************/

    private void initDoodle() {
        Bitmap bitmap = (Bitmap) BitmapLruCache.getInstance(this).get("homework_line_bg1");
        if (null == bitmap) {
            bitmap = BitmapUtil.ReadBitmapById_4444(this, R.drawable.common_caogaozhi_0);
            BitmapLruCache.getInstance(this).put("bg1", bitmap);
        }

        Bitmap bitmap2 = (Bitmap) BitmapLruCache.getInstance(this).get("homework_line_bg2");
        if (null == bitmap2) {
            LogUtils.e("initDoodle fl width:" + fl_width + ",height:" + fl_height);
            doodle_bitmap = resizeImage(bitmap, fl_width, fl_height);
        } else {
            doodle_bitmap = bitmap2;
        }
        setPicFilePath(mAssistantExamId, mQuestionCurr.getQuestionId(), mQuestionCurr.getQuestionNo(), currAnswerIndex);
        initDoodleData();
    }

    private void initDoodleData_pre() {
        if (mIsLoadImg_b_end) {
            if (doodle_bitmap == null) {
                LogUtils.e("出错了，背景图为null");
                mIsSwitchBitmaping = false;
            } else {
                flDoodle.setVisibility(View.VISIBLE);
                flDoodle.post(new Runnable() {
                    @Override
                    public void run() {
                        fl_width = flDoodle.getMeasuredWidth();
                        fl_height = flDoodle.getMeasuredHeight();
                        initDoodleData();
                    }
                });
            }
        }
    }

    private void drawBitmap() {
        if (mCurDot == null) {
            //小测点阵教辅，点击第一次进入acitivity时就是null
            LogUtils.e("mCurDot == null 小测点阵教辅，点击第一次进入acitivity时就是null");
            return;
        }
        if (mTouchGestureListener == null) {
            LogUtils.e("mTouchGestureListener == null ");
            nextDots();
            return;
        }
        mTemp_x = (TsdPenUtil.getRealX(mCurDot.coordX, mPic_w) - m_tran_x) * mDoodle.getZoomerScale();
        mTemp_y = (TsdPenUtil.getRealY(mCurDot.coordY, mPic_h) - m_tran_y) * mDoodle.getZoomerScale();

        if (mMin_h == 0) {
            mMin_h = mTemp_y;
        }
        if (mMax_h == 0) {
            mMax_h = mTemp_y;
        }
        mMin_h = Math.min(mMin_h, mTemp_y);
        mMax_h = Math.max(mMax_h, mTemp_y);


        if (mCurDot.state == TsdService.PEN_DOWN_MESSAGE) {
            mTouchGestureListener.r_onDown(mTemp_x, mTemp_y);
            mTouchGestureListener.r_onScrollBegin(mTemp_x, mTemp_y);
        } else if (mCurDot.state == TsdService.PEN_COODINAT_MESSAGE) {
            mTouchGestureListener.r_onScroll(mTemp_x, mTemp_y);
        } else if (mCurDot.state == TsdService.PEN_UP_MESSAGE) {
            mTouchGestureListener.r_onScrollEnd(mTemp_x, mTemp_y);
        }

        nextDots();
    }


    private void initDoodleData() {
        ivMyAnswer0.setVisibility(View.GONE);
        ivMyAnswer1.setVisibility(View.GONE);
        ivMyAnswer2.setVisibility(View.GONE);
//        flDoodle.setVisibility(View.VISIBLE);
        flDoodle.removeAllViews();

        mDoodleParams = new DoodleParams();
        mDoodleParams.mImagePath = picFilePath;
        mDoodleParams.mSavePath = picFilePath;
        mDoodleParams.mSavePathIsDir = false;
        mDoodleParams.mIsDrawableOutside = false;
        /*
        Whether or not to optimize drawing, it is suggested to open, which can optimize the drawing speed and performance.
        Note: When item is selected for editing after opening, it will be drawn at the top level, and not at the corresponding level until editing is completed.
        是否优化绘制，建议开启，可优化绘制速度和性能.
        注意：开启后item被选中编辑时时会绘制在最上面一层，直到结束编辑后才绘制在相应层级
         */
        mDoodle = mDoodleView = new DoodleViewWrapper(this, doodle_bitmap, false, false, new IDoodleListener() {
            @Override
            public void onSaved(IDoodle doodle, Bitmap bitmap, Runnable callback) { // 保存图片为jpg格式
                LogUtils.i("m1:涂鸦保存成功" + ", threadName = " + Thread.currentThread().getName());
                //切图
                int y = mMin_h - mTran_h < 0 ? 0 : (int) (mMin_h - mTran_h);
                //如果没有采集到笔迹的区域信息，则区域默认为全图区域
                System.out.println("onSaved:"  + "max_h = " + mMax_h);
                if (mMax_h == 0f) mMax_h = Float.valueOf(bitmap.getHeight());

                int h = (mMax_h + mTran_h - mMin_h) > bitmap.getHeight()
                        ? (int) (bitmap.getHeight() - y) : (int) (mMax_h + 2 * mTran_h - mMin_h);
                //h+y必须要小于等于bitmap.getHeight()
                if (h + y > bitmap.getHeight()) h = (int) (h - mTran_h);

                Bitmap clip_bitmap = Bitmap.createBitmap(bitmap, 0, y, bitmap.getWidth(), h);
                //保存切图
                FileUtils.saveBitmap(clip_bitmap, picClipPath);
                //当前需要上传的本地切图地址
                String uploadLocalPath = picClipPath;
                final String path = mDoodleParams.mSavePath;
                //保存原图
                FileUtils.saveBitmap(bitmap, path);
                if (mDoodleSaveType == DOODLE_SAVE_TYPE_SWITCH) {
                    LogUtils.i("m1 clip: DOODLE_SAVE_TYPE_SWITCH start");
                    if (mCurPagePictureOnLine != null) {
                        mCurPagePictureOnLine.setMin_h(mMin_h);
                        mCurPagePictureOnLine.setMax_h(mMax_h);
                    }

                    DBUtils.getInstance(HomeworkLineActivity.this).updatePagePictureOnline(mCurPagePictureOnLine);
                    PagePictureOnline pagePictureOnline = DBUtils.getInstance(HomeworkLineActivity.this)
                            .getPagePictureOnlineByPageserial(mAssistantExamId, mQuestionCurr.getQuestionId(), mCurDot.pageAddress);
                    if (null != pagePictureOnline) {
                        pagePictureOnline.setPictureUrl(null);
                        mCurPagePictureOnLine = pagePictureOnline;
                        mMin_h = mCurPagePictureOnLine.getMin_h();
                        mMax_h = mCurPagePictureOnLine.getMax_h();
                        currAnswerIndex = pagePictureOnline.getAnswerIndex();
                        picFilePath = pagePictureOnline.getLocalPath();
                        picClipPath = pagePictureOnline.getLocalClipPath();
                        switchOldPagePicture();
                    }
                } else if (mDoodleSaveType == DOODLE_SAVE_TYPE_ADD) {
                    LogUtils.i("m1 clip: DOODLE_SAVE_TYPE_ADD start");
                    if (mCurPagePictureOnLine != null) {
                        mCurPagePictureOnLine.setMin_h(mMin_h);
                        mCurPagePictureOnLine.setMax_h(mMax_h);
                    }
                    LogUtils.i("m2 update:" + mCurPagePictureOnLine.getPictureId() + "min_h" + mMin_h + ",max_h" + mMax_h);
                    DBUtils.getInstance(HomeworkLineActivity.this).updatePagePictureOnline(mCurPagePictureOnLine);
                    currAnswerIndex = getSubjectAnswerNum(mQuestionCurr);
                    switchPicData_real_add();
                    mMin_h = 0f;
                    mMax_h = 0f;
                } else if (mDoodleSaveType == DOODLE_SAVE_TYPE) {
                    LogUtils.i("m1 clip: DOODLE_SAVE_TYPE start");
                    //DialogXUtil.dismissAll();
                    llMsgTip.setVisibility(View.GONE);
                    //将切图的top和bottom位置保存
                    if (mCurPagePictureOnLine != null) {
                        mCurPagePictureOnLine.setMin_h(mMin_h);
                        mCurPagePictureOnLine.setMax_h(mMax_h);
                    }
                    LogUtils.i("m2 update:" + mCurPagePictureOnLine.getPictureId() + "min_h" + mMin_h + ",max_h" + mMax_h);
                    DBUtils.getInstance(HomeworkLineActivity.this).updatePagePictureOnline(mCurPagePictureOnLine);
                    startTimer();
                    refreshByQuestion(mQuestionCurr = mQuestionList.get(mCurrIndex));
                } else if (mDoodleSaveType == DOODLE_SAVE_TYPE_SUBMIT) {
                    //上传更新本地图片地址为网络地址后再提交
                    // DialogXUtil.dismissAll();
                    llMsgTip.setVisibility(View.GONE);
                    btNextSubmit.setClickable(true);
                    endTimer();
                    submitHomework();
                } else if (mDoodleSaveType == DOODLE_SAVE_TYPE_SUBMIT_FORCE) {
                    //上传更新本地图片地址为网络地址后再提交
                    //DialogXUtil.dismissAll();
                    llMsgTip.setVisibility(View.GONE);
                    if (isFromRoom) {
                        mIsSubmiting = false;
                    }
                } else if (mDoodleSaveType == DOODLE_SAVE_TYPE_EXIT) {
                } else if (mDoodleSaveType == DOODLE_SAVE_SCENCE_TYPE) {
                    //DialogXUtil.dismissAll();
                    llMsgTip.setVisibility(View.GONE);
                    sceneQuestionSwitch(sceneIndex, mQuestionCurr);
                    displaySceneByType(sceneIndex, mQuestionCurr);
                }

                //String uploadFile = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS").format(System.currentTimeMillis()) + "_" + FileUtils.getFileName(mDoodleParams.mSavePath);
                StringBuilder uploadFile = new StringBuilder();
                uploadFile.append(FileUtils.getFileNameNoExtension(uploadLocalPath));
                uploadFile.append("_");
                uploadFile.append(new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS").format(System.currentTimeMillis()));
                uploadFile.append(".png");

                UploadOss.getInstance().upload2OSS(uploadFile.toString(), uploadLocalPath, ossUploadListener, null);

            }

            @Override
            public void onReady(IDoodle doodle) {
                LogUtils.i("m1:-----doodle----onReady");
                //mDoodleView.setSize(2f); //这一句可以设置笔画粗细
            }
        });

        mTouchGestureListener = new DoodleOnTouchGestureListener(mDoodleView, new DoodleOnTouchGestureListener.ISelectionListener() {

            IDoodleItemListener mIDoodleItemListener = new IDoodleItemListener() {
                @Override
                public void onPropertyChanged(int property) {

                }
            };

            @Override
            public void onSelectedItem(IDoodle doodle, IDoodleSelectableItem selectableItem, boolean selected) {

            }

            @Override
            public void onCreateSelectableItem(IDoodle doodle, float x, float y) {

            }

            @Override
            public void onCallScrollBegin(MotionEvent e) {

            }

            @Override
            public void onCallScrollEnd(MotionEvent e) {

            }

            @Override
            public void onCallScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

            }

        }) {
            @Override
            public void setSupportScaleItem(boolean supportScaleItem) {
                super.setSupportScaleItem(supportScaleItem);
            }
        };
        mTouchGestureListener.setSupportScale(true); //禁止放大缩小
        setSupportDoodle(false);
        setSupportTrans(false);

        mTouchGestureListener.setTouchType(DoodleOnTouchGestureListener.TOUCH_TYPE_ALL);
        IDoodleTouchDetector detector = new DoodleTouchDetector(this, mTouchGestureListener);
        mDoodleView.setDefaultTouchDetector(detector);
        mDoodleView.setStartXy(true);
        mDoodle.setColor(new DoodleColor(Color.BLACK));

        mDoodle.setIsDrawableOutside(false);
        flDoodle.addView(mDoodleView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        DoodleParams doodleParams = new DoodleParams();
        mDoodle.setDoodleMinScale(doodleParams.mMinScale);
        mDoodle.setDoodleMaxScale(doodleParams.mMaxScale);
        mDoodle.setZoomerScale((float) fl_width / mPic_w); //比例  实际宽高/mPic_w

        mDoodle.setSize(0.5f);

        delayToDot(300);
    }

    private void delayToDot(int time) {
        Observable.timer(time, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Long aLong) {
                        LogUtils.d("m1:onNext " + aLong + ", threadName = " + Thread.currentThread().getName());
                        mIsSwitchBitmaping = false;
                        drawBitmap();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    UploadOss.OnUploadListener ossUploadListener = new UploadOss.OnUploadListener() {
        @Override
        public String uploadSuccess(String uploadFile, String localFile, OssParams ossParams) {

            Thread thread1 = getMainLooper().getThread();
            Thread thread2 = Thread.currentThread();
            LogUtils.i("-----doodle----OSSUploadListener主线程ID: " + thread1.getId());
            LogUtils.i("-----doodle----OSSUploadListener当前线程ID: " + thread2.getId());
            //isOssSuccess(uploadFile);
            PagePictureOnline pagePictureOnline = DBUtils.getInstance(HomeworkLineActivity.this)
                    .getPagePictureOnlineByPictureLocalClip(localFile);
            if (null != pagePictureOnline) {
                LogUtils.i("path==" + localFile + " : " + uploadFile);
                pagePictureOnline.setPictureUrl(uploadFile);
                DBUtils.getInstance(HomeworkLineActivity.this).updatePagePictureOnline(pagePictureOnline);
            }

            if (mDoodleSaveType == DOODLE_SAVE_TYPE_EXIT) {
                if (!isFromRoom) {
                    int emptyNum = 0;
                    for (Map.Entry<String, String> entry : mAnswerMap.entrySet()) {
                        if (TextUtils.isEmpty(entry.getValue())) {
                            ++emptyNum;
                        }
                    }
                    AssistantExamOnline examOnline = DBUtils.getInstance(HomeworkLineActivity.this).getAssistantExamOnlineByPublishId(mPublishId, mExamId, mStudentId);
                    if (null != examOnline) {
                        examOnline.setDealNum(examOnline.getTotalNum() - emptyNum);
                        examOnline.setTempAnswer(JsonUtils.toJson(mAnswerMap));
                        DBUtils.getInstance(HomeworkLineActivity.this).updateAssistantExamOnline(examOnline);
                    }

                    EventBus.getDefault().postSticky(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_ANSWER_PROGRESS,
                            mExamId + "###" + mPublishId + "###" + (null != examOnline ? examOnline.getTotalNum() - emptyNum : 0)));
                    finish();
                } else {
                    DialogXUtil.customDialogShow("您将放弃本次作答，是否确定退出？",
                            getResources().getString(R.string.ok), getResources().getString(R.string.cancel), false, new DialogXUtil.OnDialogXListen() {
                                @Override
                                public void onListenDialogOk() {
                                    clearAnswerRecord();
                                    finish();
                                }

                                @Override
                                public void onListenDialogCancel() {
                                }

                                @Override
                                public void onListenDialogClose() {
                                }
                            });
                }
            } else if (mDoodleSaveType == DOODLE_SAVE_TYPE_SUBMIT_FORCE) {
                if (isFromRoom) {
                    mIsSubmiting = true;
                    exceptionSubmitCount = 0;
                    submitHomeworkOk();
                }
            }
            return null;
        }

        @Override
        public String uploadFail(String uploadFile, String localFile, OssParams ossParams) {
            return null;
        }
    };

    private class DoodleViewWrapper extends DoodleView {

        public DoodleViewWrapper(Context context, Bitmap bitmap, boolean optimizeDrawing, boolean isMask, IDoodleListener listener) {
            super(context, bitmap, optimizeDrawing, isMask, listener);
        }
    }

    private void setSupportDoodle(boolean isSupport) {
        if (mTouchGestureListener != null) {
            mTouchGestureListener.setSupportDoodle(isSupport);
        }
    }

    private void setSupportTrans(boolean isSupport) {
        if (mTouchGestureListener != null) {
            mTouchGestureListener.setSupportTrans(isSupport);
        }
    }

    public Bitmap resizeImage(Bitmap bitmap, int width, int height) {
        int bmpWidth = bitmap.getWidth();
        int bmpHeight = bitmap.getHeight();

        float scaleWidth = ((float) width) / bmpWidth;
        float scaleHeight = ((float) height) / bmpHeight;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        return Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight, matrix, true);
    }


    private void setPicFilePath(Long mAssistantExamId, int questionId, int questionNo, int answerIndex) {
        //String dirPath = this.getExternalFilesDir(null).getAbsolutePath();
        String dirPath = Constants.FILE_PATH;
        StringBuilder dir = new StringBuilder(dirPath);
        dir.append(File.separator).append("homework_doodle");
        //dirPath = dirPath + File.separator + "homework_doodle";
        File picDirF = new File(dir.toString());
        if (!picDirF.exists()) {
            boolean mkdirs = picDirF.mkdirs();
            if (!mkdirs) {
                LogUtils.e("m1:创建失败picDir：" + dirPath);
            } else {
                LogUtils.i("m1:创建成功picDir");
            }
        }
        StringBuilder dir_clip = new StringBuilder(dir);
        picFilePath = dir.append(File.separator).append(answerIndex).append("&")
                .append(String.valueOf(mExamId)).append("_")
                .append(String.valueOf(mAssistantExamId)).append("_")
                .append(String.valueOf(questionId)).append("_")
                .append(String.valueOf(questionNo)).append("_")
                .append(".png").toString();

        picClipPath = dir_clip.append(File.separator).append(answerIndex).append("&")
                .append(String.valueOf(mExamId)).append("_")
                .append(String.valueOf(mAssistantExamId)).append("_")
                .append(String.valueOf(questionId)).append("_")
                .append(String.valueOf(questionNo)).append("_")
                .append("clip")
                .append(".png").toString();


        LogUtils.i("m1: 图片存储的路径：" + picFilePath);

    }


    @Override
    public void getQuestionListFailed() {
        //ToastUtil.initToast("考试数据异常,请联系管理员");
        finish();
    }

    @Override
    public void getCommitAnswerResult(BaseResponse<CommitAssistantAnswerResp> response) {
        if (90012 == response.getCode()) {//该试题您已经提交作答了，不能再次作答
            finish();
            return;
        }
        if (0 == response.getCode()) {
            clearAnswerRecord();
            CommitAssistantAnswerResp data = response.getData();
            EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_ANSWER_SUBMIT_SUCCESS, null));
            okAndCancelDialog(HomeworkLineActivity.this,
                    getResources().getString(R.string.homework_submit_success), "",
                    getResources().getString(R.string.homework_check_detail), true, R.drawable.common_dialog_icon_dui, new DialogXUtil.OnDialogXListen() {
                        @Override
                        public void onListenDialogOk() {

                        }

                        @Override
                        public void onListenDialogCancel() {
                            if (mIsTupu) {
                                if (data != null) {
                                    ARouter.getInstance().build(ConstantArouter.PATH_HOMEWORK_DETAILACTIVITY)
                                            .withString("examName", mExamName)
                                            .withInt("examId", mExamId)
                                            .withInt("publishId", data.getExamPublishId())
                                            .withInt("studentExamId", data.getStudentExamId())
                                            .navigation();
                                }
                            } else {
                                ARouter.getInstance().build(ConstantArouter.PATH_HOMEWORK_DETAILACTIVITY)
                                        .withString("examName", mExamName)
                                        .withInt("examId", mExamId)
                                        .withInt("publishId", mPublishId)
                                        .withInt("studentExamId", mStudentExamId)
                                        .navigation();
                            }

                            HomeworkLineActivity.this.finish();

                        }

                        @Override
                        public void onListenDialogClose() {

                        }
                    });
        } else {
            mIsSubmiting = false;
        }
    }


    public void okAndCancelDialog(final Context context, String tip, String leftTip, String rightTip, boolean isOnlyRight, int iconId, final DialogXUtil.OnDialogXListen onDialogXListen) {
        DialogXUtil.customDialogShow(tip, leftTip, rightTip, isOnlyRight, iconId, onDialogXListen);
    }


    private void clearAnswerRecord() {
        List<PagePictureOnline> listPicture = DBUtils.getInstance(this).getPagePicturesByQuestionId(mAssistantExamId);
        if (null != listPicture) {
            for (int i = 0; i < listPicture.size(); i++) {
                if (null != listPicture.get(i)) {
                    FileUtils.deleteFile(listPicture.get(i).getLocalPath());
                    FileUtils.deleteFile(listPicture.get(i).getLocalClipPath());
                }
            }
        }
        DBUtils.getInstance(this).deletePagePictureOnlineByExamId(mAssistantExamId);
        DBUtils.getInstance(this).deleteAssistantQuestionOnlineByAssistantExamId(mAssistantExamId);
        DBUtils.getInstance(this).deleteAssistantExamOnlineByPublishId(mPublishId, mExamId, mStudentId);
    }

    @Override
    public void getCommitAnswerFailed() {
        mIsSubmiting = false;
    }

    @Override
    public void queryClassroomTestQuestionListResult(BaseResponse<QueryExamQuestionsResponse> response) {
        if (null == response) return;

        QueryExamQuestionsResponse data = response.getData();
        if (null == data) return;

        mQuestionList = data.getQuestionList();
        if (null == mQuestionList || 0 == mQuestionList.size()) return;

        setAssistantExamId(mQuestionList.size());

        setQuestionAnswer(mQuestionList);
        LogUtils.i("queryClassroomTestQuestionListResult data= " + response.getData().toString());

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                display(mQuestionList);
            }
        });

    }

    @Override
    public void queryClassroomTestQuestionListFailed() {

    }

    /*
     *
     *
     ********************************点阵数据模块******************************************
     *
     */
    private boolean mIsHttping;
    private boolean mIsSwitchBitmaping;
    private volatile boolean mIsSubmiting;

    @Override
    public void setTsdServiceConnected() {
        super.setTsdServiceConnected();

        if (null != mTsdServiceBinder) {
            if (isFromRoom) {
                mMoudle = TsdService.MODULE_SMALLTEST_LINE;
            } else {
                if (mIsTupu) {
                    mMoudle = TsdService.MODULE_HOMEWORK_LINE_TUPU;
                } else {
                    mMoudle = TsdService.MODULE_HOMEWORK_LINE;
                }
            }
            mTsdServiceBinder.on_setmModule(mMoudle);
        }
    }

    @Override
    public void setTsdServiceDisConnect() {
        if (null != mTsdServiceBinder) {
            if (isFromRoom) {
                mTsdServiceBinder.on_setmModule(TsdService.MODULE_ROOM);
            } else {
                mTsdServiceBinder.on_setmModule(TsdService.MODULE_DEFAULT);
            }
        }
    }

    private CoordinateInfo mCurDot;
    private ConcurrentLinkedQueue<CoordinateInfo> mOffLineDots = new ConcurrentLinkedQueue();

    private TsdService.OnDataReceiveListener mTsdListener = new TsdService.OnDataReceiveListener() {
        @Override
        public void onFinish() {

        }

        @Override
        public void onErrTsdPen(int code, String msg) {
        }

        @Override
        public void onRefreshScan(boolean isScaning) {
        }

        @Override
        public void onAddDevice(BleDevice bleDevice) {
        }

        @Override
        public void onPenConnectStatus(int code, BleDevice bleDevice) {
        }

        @Override
        public void onGetPenInfo(int batteryPercent, int memoryPercent, int memoryByteNum) {
        }

        @Override
        public void onCoordDraw(CoordinateInfo coordinateInfo) {
            if (null != coordinateInfo) {
                LogUtils.i("onCoordDraw coordinateInfo = " + JsonUtils.toJson(coordinateInfo));
            } else {
                LogUtils.i("onCoordDraw null ==  coordinateInfo ");
            }
            if (mIsSubmiting || QuestionTypeUtil.isObjectQuestion(mQuestionCurr.getQuestionType())) {
                return;
            }

            mOffLineDots.offer(coordinateInfo);
            nextDots();
        }

        @Override
        public void onTeacherExitSmallTest() {

        }
    };

    private void nextDots() {
        LogUtils.i("nextDots mCurDot <<<<");
        while (!mIsSwitchBitmaping && !mOffLineDots.isEmpty()
                && QuestionTypeUtil.isSubjectQuestion(mQuestionCurr.getQuestionType())) {
            mCurDot = mOffLineDots.poll();
            if (null != mCurDot) {
                LogUtils.i("nextDots mCurDot = " + JsonUtils.toJson(mCurDot));
            } else {
                LogUtils.i("nextDots null ==  mCurDot ");
            }

            if (null != mCurDot && mCurDot.state == TsdService.PEN_DOWN_MESSAGE) {
                PagePictureOnline pagePictureOnline = DBUtils.getInstance(this)
                        .getPagePictureOnlineByPageserial(mAssistantExamId, mQuestionCurr.getQuestionId(), mCurDot.pageAddress);
                if (null == pagePictureOnline) { //新增一页
                    List<PagePictureOnline> pageList = DBUtils.getInstance(this)
                            .getPagePictureOnlineByPageserial(mAssistantExamId, mQuestionCurr.getQuestionId());
                    if (null != pageList && pageList.size() >= 3) {
                        ToastUtil.initToast("答题不能超过三页,请在已作答页面继续作!");
                        return;
                    }
                }
            }

            analysisDots();
        }
        LogUtils.i("nextDots mCurDot >>>>");
    }

    private void analysisDots() {
        if (null != mCurDot && mCurDot.state == TsdService.PEN_DOWN_MESSAGE) {
            LogUtils.i("mCurDot.state == TsdService.PEN_DOWN_MESSAGE");
            if (null == mCurPagePictureOnLine) {
                LogUtils.i("mCurPagePictureOnLine == null");
                switchNewPagePicture();
            } else {
                PagePictureOnline pagePictureOnline = DBUtils.getInstance(this)
                        .getPagePictureOnlineByPageserial(mAssistantExamId, mQuestionCurr.getQuestionId(), mCurDot.pageAddress);
                if (null == pagePictureOnline) { //新增一页
                    if (getSubjectAnswerNum(mQuestionCurr) >= 3) {
                        ToastUtil.initToast("答题不能超过三页,请在已作答页面继续作!");
                        return;
                    } else {
                        switchPicData_real_add_pre();
                    }
                } else {
                    if (mCurPagePictureOnLine.getPageSerial()
                            .equalsIgnoreCase(pagePictureOnline.getPageSerial())) {
                        drawBitmap();//当前页面继续画点
                    } else {//切换到之前已经作答过页面,保存当前页面
                        switchPicData_real_switch_pre();
                    }
                }
            }
        } else {
            if (mCurPagePictureOnLine == null) {
                LogUtils.e("m1: 丢弃的移动或弹起点");
            } else {
                //绘制图片
                LogUtils.i("mCurPagePictureOnLine != null drawBitmap ");
                LogUtils.i("mCurDot.state = " + mCurDot.state + " != TsdService.PEN_DOWN_MESSAGE");
                drawBitmap();
            }
        }
    }

    private void switchNewPagePicture() {
        LogUtils.i("<<<<");
        PagePictureOnline pagePictureOnline = DBUtils.getInstance(this)
                .getPagePictureOnlineByPageserial(mAssistantExamId, mQuestionCurr.getQuestionId(), mCurDot.pageAddress);
        if (null == pagePictureOnline) {///首次点击 未作答的新页面
            LogUtils.i(" null == pagePictureOnline");
            switchNew_pre();
        } else {//首次点击 之前已经作答的页面
            LogUtils.i("null != pagePictureOnline ");
            LogUtils.i("m2: switchNewPagePicture" + "min_h" + pagePictureOnline.getMin_h() + ",max_h" + pagePictureOnline.getMax_h());
            pagePictureOnline.setPictureUrl(null);
            mCurPagePictureOnLine = pagePictureOnline;
            mMin_h = mCurPagePictureOnLine.getMin_h();
            mMax_h = mCurPagePictureOnLine.getMax_h();
            currAnswerIndex = pagePictureOnline.getAnswerIndex();
            picFilePath = pagePictureOnline.getLocalPath();
            picClipPath = pagePictureOnline.getLocalClipPath();
            switchOldPagePicture();
        }
        LogUtils.i(">>>>");
    }

    private void switchOldPagePicture() {
        LogUtils.i("<<<<");
        if (!TextUtils.isEmpty(picFilePath) && new File(picFilePath).exists()) {
            LogUtils.i("picFilePath " + picFilePath + " is exist");
            mIsLoadImg_b_end = false;
            mIsSwitchBitmaping = true;
            Glide.with(this).asBitmap().load(picFilePath).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(new CustomTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            LogUtils.e("m1:Glde图片-成功  = " + mCurPagePictureOnLine.getLocalPath() + ", threadName = " + Thread.currentThread().getName());
                            doodle_bitmap = resource;
                            LogUtils.e("doodle_bitmap:" + "w=" + doodle_bitmap.getWidth() + ",h=" + doodle_bitmap.getHeight());
                            mIsLoadImg_b_end = true;
                            initDoodleData_pre();
                        }

                        @Override
                        public void onLoadFailed(@Nullable Drawable errorDrawable) {
                            super.onLoadFailed(errorDrawable);
                            LogUtils.e("m1:Glde图片-失败  = " + mCurPagePictureOnLine.getLocalPath() + ", threadName = " + Thread.currentThread().getName());
                            mIsLoadImg_b_end = true;
                            initDoodleData_pre();
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {

                        }
                    });
        } else {
            LogUtils.i("picFilePath " + picFilePath + " is not exist");
            //switchPicData_real();
        }
        LogUtils.i(">>>>");
    }

    private int getSubjectAnswerNum(StudentExamQuestion question) {
        List<PagePictureOnline> pageList = DBUtils.getInstance(this)
                .getPagePictureOnlineByPageserial(mAssistantExamId, question.getQuestionId());
        return null == pageList ? 0 : pageList.size();
    }

    private void switchNew_pre() {
        LogUtils.i("<<<<");
        int size = getSubjectAnswerNum(mQuestionCurr);
        if (size >= 3) {
            ToastUtil.initToast("答题不能超过三页,请在已作答页面继续作!");
        } else {
            mIsSwitchBitmaping = true;
            currAnswerIndex = size;
            switchPicData_real_add();
        }
        LogUtils.i("<<<<");
    }

    private int currAnswerIndex = 0;

    private void switchPicData_real_switch_pre() {
        LogUtils.d("<<<< newIndex = " + currAnswerIndex);
        mIsSwitchBitmaping = true;
        if (mDoodleView != null) {
            LogUtils.d("mDoodleView != null DOODLE_SAVE_TYPE_SWITCH");
            mDoodleSaveType = DOODLE_SAVE_TYPE_SWITCH;
            mDoodleView.save();
        } else {
            LogUtils.d("mDoodleView == null switchPicData_real");
            // switchPicData_real_add();
        }
    }

    private void switchPicData_real_add_pre() {
        LogUtils.d("<<<< newIndex = " + currAnswerIndex);
        mIsSwitchBitmaping = true;
        if (mDoodleView != null) {
            LogUtils.d("mDoodleView != null DOODLE_SAVE_TYPE_SWITCH");
            mDoodleSaveType = DOODLE_SAVE_TYPE_ADD;
            mDoodleView.save();
        } else {
            LogUtils.d("mDoodleView == null switchPicData_real");
            //  switchPicData_real_add();
        }
    }


    private void switchPicData_real_add() {
        LogUtils.d("<<<< newIndex = " + currAnswerIndex);
        StringBuilder picId = new StringBuilder();
        picId.append(String.valueOf(mAssistantExamId)).append("_")
                .append(String.valueOf(mQuestionCurr.getQuestionId())).append("_").append("" + currAnswerIndex);
        LogUtils.d("picId = " + picId.toString());
        setPicFilePath(mAssistantExamId, mQuestionCurr.getQuestionId(), mQuestionCurr.getQuestionNo(), currAnswerIndex);

        mCurPagePictureOnLine = new PagePictureOnline(null,
                mQuestionCurr.getQuestionId(), mQuestionCurr.getQuestionNo(), "", picClipPath,
                picFilePath, currAnswerIndex, 0f, 0f, picId.toString(), 0, 0, 0,
                0, mCurDot.pageAddress, mAssistantExamId);
        DBUtils.getInstance(this).insertPagePictureOnline(mCurPagePictureOnLine);


        String answer = mAnswerMap.get(mQuestionCurr.getQuestionId() + "###" + mQuestionCurr.getQuestionType());
        if (TextUtils.isEmpty(answer)) {
            mAnswerMap.put(mQuestionCurr.getQuestionId() + "###" + mQuestionCurr.getQuestionType(), picFilePath);
        } else {
            if (!answer.contains(picFilePath)) {
                mAnswerMap.put(mQuestionCurr.getQuestionId() + "###" + mQuestionCurr.getQuestionType(),
                        new StringBuilder(answer).append("###").append(picFilePath).toString());
            }
        }


        flDoodle.setVisibility(View.VISIBLE);
        flDoodle.post(new Runnable() {
            @Override
            public void run() {
                fl_height = flDoodle.getMeasuredHeight();
                fl_width = flDoodle.getMeasuredWidth();
                mMin_h = 0f;
                mMax_h = 0f;
                initDoodle();
            }
        });

        LogUtils.d(">>>> newIndex = ");
    }

    public class QuestionViewPager extends FragmentPagerAdapter {

        private List<Fragment> mFragments;

        public QuestionViewPager(Context context, FragmentManager fm) {
            super(fm);
        }

        public QuestionViewPager(Context context, FragmentManager fm, List<Fragment> fragments) {
            super(fm);
            mFragments = fragments;
        }

        @Override
        public Fragment getItem(int position) {
            return null == mFragments ? null : mFragments.get(position);
        }

        @Override
        public int getCount() {
            return null == mFragments ? 0 : mFragments.size();
        }
    }


    public interface OnNotifyUpdate {
        void onNotifyUpdate(CoordinateInfo coordinateInfo);

        void onNofityRefresh();
    }

    private OnNotifyUpdate onNotifyUpdate;

    public void setOnNotifyUpdate(OnNotifyUpdate onNotifyUpdate) {
        this.onNotifyUpdate = onNotifyUpdate;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void busGetMessage(EventBusMessage messageEvent) {
        int action = messageEvent.getAction();
        if (EventBusMessage.EVENT_BUS_ACTION_SEND_DATA_SUCCESS == action) {
            String msg = messageEvent.getMsg();
            if ("success".equals(msg)) {
                ToastUtil.initToast("提交成功！");
                if (isFromRoom) {
                    clearAnswerRecord();
                    finish();
                }
            } else {
                ToastUtil.initToast("提交失败！");
                mIsSubmiting = false;
                DialogXUtil.dismissAll();
            }
        } else if (EventBusMessage.EVENT_BUS_ACTION_WEBSOCKE_ANSWER_EXIT == action) {
            LogUtil.i("command:" + "接收到退出答题指令" + "isSubmiting" + mIsSubmiting);
            //当前题目是主观题,先保存上传然后提交
            if (mIsSubmiting) {
                return;
            }
            if (null != mQuestionCurr && QuestionTypeUtil.isSubjectQuestion(mQuestionCurr.getQuestionType())
                    && null != mCurPagePictureOnLine && null != mDoodleView) {
                btNextSubmit.setClickable(false);
                //DialogUtil.getInstance().waitingDialog(HomeworkLineActivity.this, "强制提交, 正在保存...");
                //DialogXUtil.waitDialogShow("强制提交, 正在保存...");
                llMsgTip.setVisibility(View.VISIBLE);
                tvMsg.setText("强制提交, 正在保存...");
                mDoodleSaveType = DOODLE_SAVE_TYPE_SUBMIT_FORCE;
                mDoodleView.save();
            } else {
                exceptionSubmitCount = 0;
                mIsSubmiting = true;
                submitHomeworkOk();
            }
        } else if (EventBusMessage.EVENT_BUS_ACTION_NOT_EXIT_ANSWER == action) {
            clearAnswerRecord();
            finish();
        }/*else if(EventBusMessage.EVENT_BUS_ACTION_UPLOAD_ERROR_SUBMIT == action) {
            String msg = messageEvent.getMsg();
            if(!TextUtils.isEmpty(msg)) {
                uploadSubmit(JsonUtils.fromJsonList(msg, new TypeToken<ArrayList<String>>() {}.getType()));
            }
        }*/ else if (EventBusMessage.EVENT_BUS_ACTION_ROOM_CONNECT_STATE == action) {
            String msg = messageEvent.getMsg();
            if ("false".equals(msg)) {
                mJoinRoom = false;
            } else {
                mJoinRoom = true;
            }
        }
    }


    /**
     * 计时
     */

    private void startTimer() {
        if (mTimerMap.get(mCurrIndex) != null) {
            secondRecord = mTimerMap.get(mCurrIndex);
        } else {
            secondRecord = 0;
        }
        //LogUtils.i("timer: start" + secondRecord);
        timerHandler.post(mTicker);
    }

    private void endTimer() {
        mTimerMap.put(mCurrIndex, secondRecord);
        secondRecord = 0;
        timerHandler.removeCallbacks(mTicker);
    }

    private Handler timerHandler = new Handler(Looper.getMainLooper());
    private final Runnable mTicker = new Runnable() {
        public void run() {
            long now = SystemClock.uptimeMillis();
            long next = now + (1000 - now % 1000);
            secondRecord++;
            //LogUtils.i("timer:" + secondRecord + ",next=" + next);
            timerHandler.postAtTime(mTicker, next);
        }
    };
}
